package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.exception.BysjException;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.SchoolServiceImpl;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/schoolCreateController")
public class SchoolCreateController extends HttpServlet {

    private SchoolServiceImpl schoolService = ServiceFactory.getService(SchoolServiceImpl.class,"SchoolServiceImpl");
    //private SchoolServiceImpl schoolService = SchoolServiceImpl.getInstance();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String school_json = JSONUtil.getJSON(req);
        School schoolToAdd = JSON.parseObject(school_json,School.class);
        resp.setContentType("application/json;charset=utf-8");
        JSONObject message = new JSONObject();
        try{
            schoolService.add(schoolToAdd);
            message.put("msg","增加成功");
            message.put("code","200");
        }catch (SQLException e) {
            message.put("message", "数据库操作异常");
            message.put("code","200");
        } catch (Exception e) {
            message.put("message", "网络异常");
            message.put("code","200");
        }
        resp.getWriter().println(JSON.toJSONString(message));
    }
}
